﻿using System;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Maps.MapControl;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
using System.ComponentModel;
using System.ServiceModel;
using System.Windows.Threading;
using System.Windows.Controls.DataVisualization.Charting;
using System.Text.RegularExpressions;



namespace map1
{
    public partial class MainPage : UserControl
    {
        //backgroundworker code courtesy msdn.microsoft.com
        private BackgroundWorker bw = new BackgroundWorker();
        private BackgroundWorker bwdownload = new BackgroundWorker();

        public MainPage()
        {
            InitializeComponent();
            //trial for treeview
            //LoadData();
            //mapDG.Mode = new AerialMode();
            //trial for xml reader for listbox and treeview (ontology)
            Uri url = new Uri("getOntologyTree.xml", UriKind.Relative);
            WebClient clientDG = new WebClient();
            clientDG.DownloadStringCompleted += new DownloadStringCompletedEventHandler(clientDG_DownloadStringCompleted);
            clientDG.DownloadStringAsync(url);

            //trial for xml reader for capturing webservices
            Uri url_web = new Uri("WebServices.xml", UriKind.Relative);
            WebClient clientADG = new WebClient();
            clientADG.DownloadStringCompleted += new DownloadStringCompletedEventHandler(clientADG_DownloadStringCompleted);
            clientADG.DownloadStringAsync(url_web);

            //trial for xml reader for getting the us states coordinates (lat,long)
            Uri url_states = new Uri("us_states_coordinates.xml", UriKind.Relative);
            WebClient clientStates = new WebClient();
            clientStates.DownloadStringCompleted += new DownloadStringCompletedEventHandler(clientStates_DownloadStringCompleted);
            clientStates.DownloadStringAsync(url_states);

            //trial for backgroundworker bw and bwdownload
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

            bwdownload.WorkerReportsProgress = true;
            bwdownload.WorkerSupportsCancellation = true;
            bwdownload.DoWork += new DoWorkEventHandler(bwdownload_DoWork);
            bwdownload.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwdownload_RunWorkerCompleted);
            bwdownload.ProgressChanged += new ProgressChangedEventHandler(bwdownload_ProgressChanged);
        }
        #region for reading states file coordinates
        
        void clientStates_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            LocationCollection lc = new LocationCollection();
            Location loc = new Location();
            LocationCollection lc1 = new LocationCollection();
            Location loc1 = new Location();
            LocationCollection lc2 = new LocationCollection();
            Location loc2 = new Location();
            //throw new NotImplementedException();
            if (e.Error == null)
            {
                StringReader stream = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(stream);

                reader.MoveToContent();
                bool isIdaho = false;
                bool isNewmexico = false;
                bool isNevada = false;
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "state")
                    {
                        //MessageBox.Show("1");
                        if (true == reader.MoveToFirstAttribute())
                        {
                            //Check for Target states
                            if (reader.Value.ToString() == "Idaho")
                            {
                                isIdaho = true;
                            }
                            else
                            {
                                isIdaho = false;
                            }
                            //end for Idaho
                            //New Mexico
                            if (reader.Value.ToString() == "New Mexico")
                            {
                                isNewmexico = true;
                            }
                            else
                            {
                                isNewmexico = false;
                            }
                            //Nevada
                            if (reader.Value.ToString() == "Nevada")
                            {
                                isNevada = true;
                            }
                            else
                            {
                                isNevada = false;
                            }
                        }
                    }
                    //for Idaho
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "point" && isIdaho == true)//bool isIdaho
                    {
                        //add point to list
                        reader.MoveToFirstAttribute();
                        string lat = reader.Value;
                        reader.MoveToNextAttribute();
                        string lon = reader.Value;
                        loc = new Location();
                        loc.Latitude = Convert.ToDouble(lat);
                        loc.Longitude = Convert.ToDouble(lon);
                        lc.Add(loc);
                    }
                    //for New Mexico
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "point" && isNewmexico == true)//bool isIdaho
                    {
                        //add point to list
                        reader.MoveToFirstAttribute();
                        string lat = reader.Value;
                        reader.MoveToNextAttribute();
                        string lon = reader.Value;
                        loc1 = new Location();
                        loc1.Latitude = Convert.ToDouble(lat);
                        loc1.Longitude = Convert.ToDouble(lon);
                        lc1.Add(loc1);
                    }
                    //for Nevada
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "point" && isNevada == true)//bool isIdaho
                    {
                        //add point to list
                        reader.MoveToFirstAttribute();
                        string lat = reader.Value;
                        reader.MoveToNextAttribute();
                        string lon = reader.Value;
                        loc2 = new Location();
                        loc2.Latitude = Convert.ToDouble(lat);
                        loc2.Longitude = Convert.ToDouble(lon);
                        lc2.Add(loc2);
                    }
                }
            }
            //adding the polygon..
            //for Idaho
            MapPolygon pgIdaho = new MapPolygon();
            pgIdaho.Fill = new SolidColorBrush(Colors.Red);
            pgIdaho.Stroke = new SolidColorBrush(Colors.Yellow);
            pgIdaho.StrokeThickness = 0.5;
            pgIdaho.Opacity = 0.3;
            pgIdaho.Locations = lc;
            //MessageBox.Show(lc.Count.ToString());
            //add the polygon
            pgIdaho.Name = "ID";
            mapDG.Children.Add(pgIdaho);
            //for New Mexico
            MapPolygon pgNewmexico = new MapPolygon();
            pgNewmexico.Fill = new SolidColorBrush(Colors.Red);
            pgNewmexico.Stroke = new SolidColorBrush(Colors.Yellow);
            pgNewmexico.StrokeThickness = 0.5;
            pgNewmexico.Opacity = 0.3;
            pgNewmexico.Locations = lc2;
            //MessageBox.Show(lc.Count.ToString());
            //add the polygon
            pgNewmexico.Name = "NM";
            mapDG.Children.Add(pgNewmexico);
            //Nevada
            MapPolygon pgNevada = new MapPolygon();
            pgNevada.Fill = new SolidColorBrush(Colors.Red);
            pgNevada.Stroke = new SolidColorBrush(Colors.Yellow);
            pgNevada.StrokeThickness = 0.5;
            pgNevada.Opacity = 0.3;
            pgNevada.Locations = lc1;
            //MessageBox.Show(lc.Count.ToString());
            //add the polygon
            pgNevada.Name = "NV";
            mapDG.Children.Add(pgNevada);

            //fill the comboboxes for loading shapes  **trial***
            cbWatershedtype.Items.Add("Regions");
            cbWatershedtype.SelectedIndex = 0;
            cbAdmintype.Items.Add("States");
            cbAdmintype.Items.Add("Counties");
            cbAdmintype.SelectedIndex = 0;
            cbWatershedvalue.Items.Add("Arkansas-White-Red Region");
            cbWatershedvalue.Items.Add("Pacific Northwest Region");
            cbWatershedvalue.Items.Add("Upper Mississippi Region");
            cbWatershedvalue.Items.Add("Alaska Region");
            cbWatershedvalue.Items.Add("New England Region");
            cbWatershedvalue.Items.Add("Rio Grande Region");

            cbWatershedvalue.Items.Add("California Region");
            cbWatershedvalue.Items.Add("Souris-Red-Rainy Region");
            cbWatershedvalue.Items.Add("Missouri Region");
            cbWatershedvalue.Items.Add("Texas-Gulf Region");

            cbWatershedvalue.Items.Add("Lower Colorado Region");
            cbWatershedvalue.Items.Add("Tennessee Region");
            cbWatershedvalue.Items.Add("Lower Mississippi Region");
            cbWatershedvalue.Items.Add("Ohio Region");

            cbWatershedvalue.Items.Add("Caribbean Region");
            cbWatershedvalue.Items.Add("Great Lakes Region");
            cbWatershedvalue.Items.Add("Hawaii Region");
            cbWatershedvalue.Items.Add("South Atlantic-Gulf Region");

            cbWatershedvalue.Items.Add("Mid Atlantic Region");
            cbWatershedvalue.Items.Add("Upper Colorado Region");
            cbWatershedvalue.Items.Add("Great Basin Region");
            cbWatershedvalue.SelectedIndex = -1;
        }
        #endregion
        #region load Data for TreeView
        private void LoadData()
        {
            List<Category> categories = new List<Category>();
            XDocument categoriesXML = XDocument.Load("getOntologyTree.xml");
            categories = this.GetCategories(categoriesXML.Element("OntologyNode"));
            tvKeywords.ItemsSource = categories;
        }
        private List<Category> GetCategories(XElement element)
        {
            return (from category in element.Elements("keyword")
                    select new Category()
                    {
                        //Name = category.Attribute("name").Value,
                        Name = category.Name.ToString(),
                        SubCategory = this.GetCategories(category)
                    }).ToList();
        }
        #endregion load Data for TreeView

        #region backgroundworker bw code
        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ////update progress bar and related text block
            //int progVal = e.ProgressPercentage;
            //if (progVal > 100) progVal = 100;
            //if (progVal < 0) progVal = 0;
            //progBarSeries.Value = e.ProgressPercentage;
            //progressText.Text = e.UserState.ToString();
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                lblSearchResult.Content = "Cancelled by User!!";
            }
            else if (e.Error != null)
            {
                lblSearchResult.Content = "Error: " + e.Error.Message;
            }
            else
            {
                int count = 0;
                if (dgSeriesList.ItemsSource != null)
                {
                    count = dgSeriesList.ItemsSource.OfType<Object>().Count();
                }
                lblSearchResult.Content = "Data Series Found:" + count;
            }
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            SearchCriteria parameters;

            if (!e.Argument.GetType().Equals(typeof(SearchCriteria)))
            {
                throw new ArgumentException("Bad Arugment should be of type SearchCriteria.");
            }
            else
            {
                parameters = (SearchCriteria)e.Argument;

                //cast parameters
                SearchCriteria.AreaRectangle rectangle = parameters.areaParameter as SearchCriteria.AreaRectangle;
                //stringbuilder
                StringBuilder url = new StringBuilder();
                
                //cultureinfo
                CultureInfo usaFormat = new CultureInfo("en-US");
                 url.Append("http://www.hydroweb.info/getcatalogservice.php");
                //url.Append("http://http://www.westernconsortium.org/his/getcatalogservice.php");
                //url.Append("?");
                //url.Append(parameters.hisCentralURL);
                //url.Append("/GetSeriesCatalogForBox2");
                url.Append("?xmin=");
                url.Append(HttpUtility.UrlEncode(rectangle.xMin.ToString(usaFormat)));
                url.Append("&xmax=");
                url.Append(HttpUtility.UrlEncode(rectangle.xMax.ToString(usaFormat)));
                url.Append("&ymin=");
                url.Append(HttpUtility.UrlEncode(rectangle.yMin.ToString(usaFormat)));
                url.Append("&ymax=");
                url.Append(HttpUtility.UrlEncode(rectangle.yMax.ToString(usaFormat)));

                //append the keyword
                url.Append("&conceptKeyword=");
                if (!String.IsNullOrEmpty(parameters.keywords.ToString()))
                {
                    url.Append(HttpUtility.UrlEncode(parameters.keywords[0].ToString()));
                }

                //int[] serviceIDs;
                //to append the list of networkIDs separated by comma
                url.Append("&networkIDs=");
                if (parameters.serviceIDs != null)
                {
                    StringBuilder serviceParam = new StringBuilder();
                    for (int i = 0; i < parameters.serviceIDs.Count - 1; i++)
                    {
                        serviceParam.Append(parameters.serviceIDs[i]);
                        serviceParam.Append(",");
                    }
                    if (parameters.serviceIDs.Count > 0)
                    {
                        serviceParam.Append(parameters.serviceIDs[parameters.serviceIDs.Count - 1]);
                    }
                    url.Append(HttpUtility.UrlEncode(serviceParam.ToString()));
                }

                //append the dates
                url.Append("&beginDate=");
                url.Append(HttpUtility.UrlEncode(parameters.startDate.ToString("MM/dd/yyyy")));

                url.Append("&endDate=");
                url.Append(HttpUtility.UrlEncode(parameters.endDate.ToString("MM/dd/yyyy")));

                //to encode the url
                string finalURL = url.ToString();

                //sending HTTPweb request trial
                //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(finalURL + "&appkey=http%3A%2F%2Fsilverlight.net&type=xml"));
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(finalURL));
                request.BeginGetResponse(new AsyncCallback(ReadCallback),
                request);

            }
            //popman();

        }
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            List<SeriesDataCart> seriesList = new List<SeriesDataCart>();
            try
                {
                    HttpWebRequest request =
                      (HttpWebRequest)asynchronousResult.AsyncState;
                    HttpWebResponse response =
                      (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                    using (StreamReader streamReader1 =
                      new StreamReader(response.GetResponseStream()))
                    {
                        //string resultString = streamReader1.ReadToEnd();

                        //resultBlock.Text = "Using HttpWebRequest: " + resultString;
                        //using XmlReader dgr = XmlReader.Create(streamReader1))
                        //catch exception
                
                            using (XmlReader dgReader = XmlReader.Create(streamReader1))
                            {
                                while (dgReader.Read())
                                {
                                    if (dgReader.NodeType == XmlNodeType.Element)
                                    {
                                        if (dgReader.Name == "SeriesRecord")
                                        {

                                            //Read the site information
                                            SeriesDataCart series = ReadSeriesFromHISCentral(dgReader);
                                            if (series != null)
                                            {
                                                seriesList.Add(series);
                                            }
                                        }
                                    }
                                }
                            }
                            dgSeriesList.Dispatcher.BeginInvoke(new Action(delegate()
                            {

                                //attach the series to datagridview using the main UI thread
                                dgSeriesList.ItemsSource = seriesList;

                                //take care of the map pushpins
                                //mapDG.Children.Clear();
                                MapLayer pushpinLayer = new MapLayer();
                                pushpinLayer.Name = "pinsSeriesFound";
                                mapDG.Children.Add(pushpinLayer);

                                foreach (var series in seriesList)
                                {
                                    var pin = new Pushpin();
                                    pin.Location = new Location(series.Latitude, series.Longitude);
                                    pin.Name = series.SiteCode;
                                    pin.Content = series.ServCode;

                                    try
                                    {
                                        //how pin looks like?
                                        pin.Background = new SolidColorBrush(Colors.Blue);
                                        //add the pins
                                        pushpinLayer.AddChild(pin, pin.Location);
                                    }
                                    catch (Exception)
                                    {
                                        // swallow
                                    }
                                    //tooltip service initiation
                                    //ToolTipService.SetToolTip(pin, series.ServCode + "," + series.SiteName);
                                    //ToolTipService.SetToolTip(pin, series.ServCode + "\r\n" + series.SiteName);
                                    pin.FontSize = 9;
                                    pin.Title = series.ServCode;
                                    pin.Description = series.SiteName;

                                    ToolTipService.SetToolTip(pin, new ToolTip()
                                    {
                                        DataContext = pin,
                                        Style = Application.Current.Resources["CustomInfoboxStyle"] as Style
                                    });
                                }
                                //close the popDG (wait form)
                                popDG.IsOpen = false;
                                //populate the result
                                int count = 0;
                                if (dgSeriesList.ItemsSource != null)
                                {
                                    count = dgSeriesList.ItemsSource.OfType<Object>().Count();

                                }
                                if (count > 0)
                                {
                                    lblSearchResult.Visibility = Visibility.Visible;
                                    cbEnableSelection.Visibility = Visibility.Visible;
                                    lblSearchResult.Content = "Data Series Found:" + count;
                                    cbEnableSelection.IsChecked = true;
                                    cbSelectArea.IsChecked = false;
                                    rectSelectPushpins.Visibility = Visibility.Visible;
                                    rectSelectMapArea.Visibility = Visibility.Collapsed;

                                    btnDownload.Visibility = Visibility.Visible;
                                }

                                //enable the form
                                this.IsEnabled = true;
                            }
                             ));
                           }
                        }
            catch (Exception e)
            {
                //Console.WriteLine("{0} Exception caught.", e);
                Dispatcher.BeginInvoke(new Action(delegate()
                {
                    //MessageBox.Show(e.Message);
                    MessageBox.Show("Oops! Cant download the file right now, Please try again with different query parameters. Error Message: " + e.Message);
                    popDG.IsOpen = false;
                    this.IsEnabled = true;
                }));
            }
        }

        private SeriesDataCart ReadSeriesFromHISCentral(XmlReader r)
        {
            CultureInfo usaCulture = new CultureInfo("en-US");

            SeriesDataCart series = new SeriesDataCart();
            while (r.Read())
            {
                string nodeName = r.Name.ToLower();

                if (r.NodeType == XmlNodeType.Element)
                {

                    switch (nodeName)
                    {
                        case "servcode":
                            r.Read();
                            series.ServCode = r.Value;
                            break;
                        case "servurl":
                            r.Read();
                            series.ServURL = r.Value;
                            break;
                        case "location":
                            r.Read();
                            series.SiteCode = r.Value;
                            break;
                        case "varcode":
                            r.Read();
                            series.VariableCode = r.Value;
                            break;
                        case "varname":
                            r.Read();
                            series.VariableName = r.Value;
                            break;
                        case "begindate":
                            r.Read();
                            series.BeginDate = Convert.ToDateTime(r.Value, usaCulture);
                            break;
                        case "enddate":
                            r.Read();
                            series.EndDate = Convert.ToDateTime(r.Value, usaCulture);
                            break;
                        case "valuecount":
                            r.Read();
                            series.ValueCount = Convert.ToInt32(r.Value);
                            break;
                        case "sitename":
                            r.Read();
                            series.SiteName = r.Value;
                            break;
                        case "latitude":
                            r.Read();
                            series.Latitude = Convert.ToDouble(r.Value, CultureInfo.InvariantCulture);
                            break;
                        case "longitude":
                            r.Read();
                            series.Longitude = Convert.ToDouble(r.Value, CultureInfo.InvariantCulture);
                            break;
                        case "datatype":
                            r.Read();
                            series.DataType = r.Value;
                            break;
                        case "valuetype":
                            r.Read();
                            series.ValueType = r.Value;
                            break;
                        case "samplemedium":
                            r.Read();
                            series.SampleMedium = r.Value;
                            break;
                        case "timeunits":
                            r.Read();
                            series.TimeUnit = r.Value;
                            break;
                        case "conceptkeyword":
                            break;
                        case "gencategory":
                            r.Read();
                            series.GeneralCategory = r.Value;
                            break;
                        case "timesupport":
                            r.Read();
                            series.TimeSupport = Convert.ToDouble(r.Value, CultureInfo.InvariantCulture);
                            break;
                    }
                }
                else if (r.NodeType == XmlNodeType.EndElement && nodeName == "seriesrecord")
                {
                    return series;
                }
            }

            return null;
        }

        #endregion backgroundworker bw code

        void clientADG_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            List<ListItem> list = new List<ListItem>();
            //try to capture the webservices from this detail
            if (e.Error == null)
            {
                StringReader stream = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(stream);
                string keywordName = string.Empty;

                reader.MoveToContent();//check the significance of this line of code
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "Title")
                    {
                        list.Add(new ListItem { Name = reader.ReadElementContentAsString(), IsChecked = true });
                        //to capture ServiceID for the search
                        reader.ReadToNextSibling("ServiceID");
                        lbWebServicesSupport.Items.Add(reader.ReadElementContentAsString());
                    }
                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Title")
                    {
                        break;
                    }
                }
                //attaching the Item source to list box
                lbWebServices.ItemsSource = list;
            }
        }


        void clientDG_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                StringReader stream = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(stream);

                string keywordName = string.Empty;

                reader.MoveToContent();

                //create a list collection/ as this may help in sorting....
                List<string> lString = new List<string>();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "keyword")
                    {
                        lString.Add(reader.ReadElementContentAsString());
                    }
                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "keyword")
                    {
                        break;
                    }
                }
                // This would sort the list and then pinpoint the Itemsource to Listbox!
                var newList = lString.OrderBy(x => x).ToList();

                //listbox containing keywords is populated here....
                lbKeywords.ItemsSource = newList;
            }
            if (e.Error == null)
            {
                TreeViewItem areaItem = null;
                TreeViewItem rootitem = new TreeViewItem();
                rootitem.Header = "HIS Keywords";
                tvKeywords.Items.Add(rootitem);

                StringReader stream = new StringReader(e.Result);
                XmlReader reader = XmlReader.Create(stream);
                string imageName = String.Empty;
                string areaName = String.Empty;
                string fileName = String.Empty;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == "keyword")
                        {
                            //if (true == reader.MoveToElement())
                            //{
                            areaName = reader.ReadElementContentAsString();
                            //MessageBox.Show(areaName);
                            areaItem = new TreeViewItem();
                            areaItem.Header = areaName;
                        }
                        else if (reader.Name == "Image")
                        {
                            if (true == reader.MoveToFirstAttribute())
                            {
                                imageName = reader.Value;
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        fileName = reader.Value;
                        TreeViewItem imageItem = new TreeViewItem();
                        imageItem.Header = imageName;
                        imageItem.Tag = fileName;
                        if (null != areaItem)
                            areaItem.Items.Add(imageItem);
                    }
                }
            }
        }
        //both radio buttons address to rbManual_click event
        private void rbManual_Click(object sender, RoutedEventArgs e)
        {
            if (rbManual.IsChecked == true)
            {
                txtboxALat.IsEnabled = true;
                txtboxALong.IsEnabled = true;
                txtboxBLat.IsEnabled = true;
                txtboxBLong.IsEnabled = true;
                btnManual.Visibility = Visibility.Visible;
            }
            if (rbMap.IsChecked == true)
            {
                txtboxALat.IsEnabled = false;
                txtboxALong.IsEnabled = false;
                txtboxBLat.IsEnabled = false;
                txtboxBLong.IsEnabled = false;
                btnManual.Visibility = Visibility.Collapsed;
            }
        }
        //this is an important point where check for all controls would happen for formload or usercontrol_load
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //1. Dates get selected here
            datepickEnd.SelectedDate = DateTime.Now;
            datepickStart.SelectedDate = DateTime.Now.AddYears(-3);
        }

        private void checkboxWebServices_Click(object sender, RoutedEventArgs e)
        {
            if (checkboxWebServices.IsChecked == true)
            {
                lbWebServices.Visibility = Visibility.Visible;
                cbSelectAll.Visibility = Visibility.Visible;
                cbSelectAll.IsChecked = true;
            }
            else
            {
                lbWebServices.Visibility = Visibility.Collapsed;
                cbSelectAll.Visibility = Visibility.Collapsed;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            foreach (ListItem item in lbWebServices.Items)
            {
                item.IsChecked = true;
            }
            webservices_update(null, null);
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (ListItem item in lbWebServices.Items)
            {
                item.IsChecked = false;
            }
            webservices_update(null, null);
        }


        public class ListItem : INotifyPropertyChanged
        {
            private string name;

            public string Name
            {
                get { return name; }
                set
                {
                    name = value;
                    RaiseEvent("Name");
                }
            }

            private bool isChecked;

            public bool IsChecked
            {
                get { return isChecked; }
                set
                {
                    isChecked = value;
                    RaiseEvent("IsChecked");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            void RaiseEvent(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

        private void tboTypeKeyword_TextChanged(object sender, TextChangedEventArgs e)
        {
            //string searchstring2;
            lbKeywords.SelectedIndex = -1;

            for (int i = 0; i < lbKeywords.Items.Count; i++)
            {
                string currentName;
                currentName = lbKeywords.Items[i].ToString().ToLower();
                if (currentName.StartsWith(tboTypeKeyword.Text.ToLower()))
                {
                    lbKeywords.SelectedIndex = i;
                    //lbKeywords.ScrollIntoView(i);
                    break;
                }
            }
        }


        private void lbKeywords_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            if (lbKeywords.SelectedIndex != -1)
            {
                String keyItem = lbKeywords.SelectedItem.ToString();
                //add the keyword to Listbox selected keywords
                lbSelectedKeywords.Items.Clear();
                lbSelectedKeywords.Items.Add(keyItem);
                btnK.BorderBrush = new SolidColorBrush(Colors.Green);
            
                // call fill search summary
                fillSearchSummary(null, null);
                //populate textbox and treeview and get the trigger word from this instance
                tboTypeKeyword.Text = keyItem;
                //space for the treeview trigger
            }

        }

        private void mapDG_MouseDragBox(object sender, MapMouseDragEventArgs e)
        {
            if (cbSelectArea.IsChecked == true)
            {
                btnDownload.Visibility = Visibility.Collapsed;
                if (rbMap.IsChecked == true)
                {

                    // Set a variable equal to the Map that raised the event
                    //e.Handled = true;
                    Map mapDG = (Map)sender;

                    //capture the starting location
                    var aLocation = mapDG.ViewportPointToLocation(e.FromViewportPoint);
                    txtboxALat.Text = aLocation.Latitude.ToString();
                    txtboxALong.Text = aLocation.Longitude.ToString();

                    //capture the end location
                    var bLocation = mapDG.ViewportPointToLocation(e.ViewportPoint);
                    txtboxBLat.Text = bLocation.Latitude.ToString();
                    txtboxBLong.Text = bLocation.Longitude.ToString();
                    mapDG.Children.Clear();
                    ////for drawing rectangle capture the lat and long
                    double a = aLocation.Latitude;
                    double b = aLocation.Longitude;
                    double c = bLocation.Latitude;
                    double d = bLocation.Longitude;

                    MapPolygon polygon = new MapPolygon();
                    polygon.Fill = new SolidColorBrush(Colors.Yellow);
                    polygon.Stroke = new SolidColorBrush(Colors.Red);
                    polygon.StrokeThickness = 5;
                    polygon.Opacity = 0.3;
                    polygon.Locations = new LocationCollection() 
                { 
                    new Location(a, b), 
                    new Location(a, d), 
                    new Location(c, d), 
                    new Location(c, b) 
                };

                    //mapDG.AddChild(polygon);
                    mapDG.Children.Add(polygon);
                    fillSearchSummary(null, null);
                    webservices_update(null, null);
                    btnColor();
                }
                else
                {
                    mapDG.Children.Clear();
                    txtboxALat.Text = "";
                    txtboxALong.Text = "";
                    txtboxBLat.Text = "";
                    txtboxBLong.Text = "";
                    fillSearchSummary(null, null);
                    webservices_update(null, null);
                }
                tabSearch.SelectedIndex = 2;
                dgSeriesList.ItemsSource = null;
                lblSearchResult.Visibility = Visibility.Collapsed;
                cbEnableSelection.Visibility = Visibility.Collapsed;
            }
            else if (cbEnableSelection.IsChecked == true)
            {
                // Set a variable equal to the Map that raised the event
                //Map mapDG = (Map)sender;

                //capture the starting location
                var xLocation = mapDG.ViewportPointToLocation(e.FromViewportPoint);


                //capture the end location
                var yLocation = mapDG.ViewportPointToLocation(e.ViewportPoint);
                ////for drawing rectangle capture the lat and long
                double a = xLocation.Latitude;
                double b = xLocation.Longitude;
                double c = yLocation.Latitude;
                double d = yLocation.Longitude;

                //clear the datagrid
                dgSeriesList.SelectedItems.Clear();

                foreach (UIElement element in mapDG.Children)
                {
                    var mapLayer = element as MapLayer;
                    if (mapLayer != null)
                    //"pinsSeriesFound"
                    {
                        if (mapLayer.Name == "pinsSeriesFound")
                        {

                            foreach (var p in mapLayer.Children)
                            {
                                var pin = p as Pushpin;
                                //how pin looks like?
                                pin.Background = new SolidColorBrush(Colors.Blue);

                                if (p != null)
                                {
                                    var z = pin.Location;
                                    double x = z.Latitude;
                                    double y = z.Longitude;

                                    if (b > d)
                                    {
                                        if (b >= x && d <= y && a >= x && c <= x)
                                        {
                                            //Change the color of the pin
                                            pin.Background = new SolidColorBrush(Colors.Orange);
                                            match(x, y);
                                        }
                                    }
                                    else
                                    {
                                        if (b <= y && d >= y && a >= x && c <= x)
                                        {
                                            //change the color of the pin
                                            pin.Background = new SolidColorBrush(Colors.Orange);
                                            match(x, y);
                                        }
                                    }
                                }
                            }

                        }

                    }
                }
            }
            int count = 0;
            count = dgSeriesList.SelectedItems.Count;
            if (count > 0) lblSelectedPins.Content = "Data Series Selected:" + count;
            else lblSelectedPins.Content = "No Data Series Selected";

        }


        private void match(double x, double y)
        {
            if (dgSeriesList.ItemsSource != null)
            {
                foreach (var rowitem in dgSeriesList.ItemsSource)
                {
                    var cart = rowitem as SeriesDataCart;
                    if (cart != null)
                    {
                        if (cart.Latitude == x && cart.Longitude == y)
                            dgSeriesList.SelectedItems.Add(cart);

                    }

                }

            }
        }
        //code courtesy: Microsoft website http://msdn.microsoft.com/en-us/library/ee681897.aspx
        // A collection of key/value pairs containing the event name  
        // and the number of times the event fired.
        Dictionary<string, int> eventCount = new Dictionary<string, int>();
        // A collection of key/value pairs containing the event name 
        // and the text block to display the event to.
        Dictionary<string, TextBlock> eventBlocks = new Dictionary<string, TextBlock>();


        //check mouseclick events and explore it for further possibilities
        private void mapDG_MouseClick(object sender, MapMouseEventArgs e)
        {
            // Updates the count of single mouse clicks.
            ShowEvent("mapDG_MouseClick");

            switch (eventCount["mapDG_MouseClick"] % 3)
            {
                case 0:
                    mapDG.Mode = new RoadMode();
                    break;
                case 1:
                    mapDG.Mode = new AerialMode();
                    break;
                case 2:
                    //"(true)" would ensure that aerial mode with labels is displayed
                    mapDG.Mode = new AerialMode(true);
                    //mapDG.Culture = "fr-fr";
                    break;
            }
            // The event has been handled by this custom handler, disabling
            // the default single-click behavior.
            e.Handled = true;
        }
        void ShowEvent(string eventName)
        {
            // Updates the display box showing the number of times 
            // the wired events occured.
            if (!eventBlocks.ContainsKey(eventName))
            {
                TextBlock tb = new TextBlock();
                tb.Foreground = new SolidColorBrush(
                    Color.FromArgb(255, 128, 255, 128));
                tb.Margin = new Thickness(5);
                eventBlocks.Add(eventName, tb);
                eventCount.Add(eventName, 0);
                //eventsPanel.Children.Add(tb);
            }
            eventCount[eventName]++;
        }

        private void btnManual_Click(object sender, RoutedEventArgs e)
        {
            //check for valid values in all text boxes
            foreach (TextBox box in this.gridLatLong.Children.OfType<TextBox>().Where(tb => string.IsNullOrEmpty(tb.Text)))
            {
                MessageBox.Show("Please provide valid data in all Textboxes (Lat & Long)");
                btnA.BorderBrush = new SolidColorBrush(Colors.Cyan);
                btnB.BorderBrush = new SolidColorBrush(Colors.Cyan);
                return;
            }

            ////for drawing rectangle capture the lat and long
            double a = Convert.ToDouble(txtboxALat.Text);
            double b = Convert.ToDouble(txtboxALong.Text);
            double c = Convert.ToDouble(txtboxBLat.Text);
            double d = Convert.ToDouble(txtboxBLong.Text);

            mapDG.Children.Clear();

            MapPolygon polygon = new MapPolygon();
            polygon.Fill = new SolidColorBrush(Colors.Yellow);
            polygon.Stroke = new SolidColorBrush(Colors.Red);
            polygon.StrokeThickness = 5;
            polygon.Opacity = 0.3;
            polygon.Locations = new LocationCollection() 
            { 
                new Location(a, b), 
                new Location(a, d), 
                new Location(c, d), 
                new Location(c, b) 
            };

            //mapDG.AddChild(polygon);
            mapDG.Children.Add(polygon);
            btnColor();

        }

        private void fillSearchSummary(object sender, TextChangedEventArgs e)
        {
            lbl_A_Value.Content = txtboxALat.Text + ' ' + ',' + ' ' + txtboxALong.Text;
            lbl_B_Value.Content = txtboxBLat.Text + ' ' + ',' + ' ' + txtboxBLong.Text;

            //for dates
            lbl_StartDate_Value.Content = datepickStart.Text;
            lbl_EndDate_Value.Content = datepickEnd.Text;

            //for keywords
            string sValue = "";
            for (int i = 0; i < lbSelectedKeywords.Items.Count; i++)
            {
                if (i == 0)
                {
                    sValue = Convert.ToString(lbSelectedKeywords.Items[0]);
                }
                else
                    sValue = sValue + " , " + Convert.ToString(lbSelectedKeywords.Items[i]);
            }
            lbl_Keywords_Value.Text = sValue;

            //for webservices
            string wValue = "";
            for (int j = 0; j < lbSelectedWebservices.Items.Count; j++)
            {
                if (j == 0)
                {
                    wValue = Convert.ToString(lbSelectedWebservices.Items[0]);
                }
                else
                    wValue = wValue + " , " + Convert.ToString(lbSelectedWebservices.Items[j]);
            }
            lbl_WebServices_Value.Text = wValue;
        }

        private void btnAddkeyword_Click(object sender, RoutedEventArgs e)
        {
            if (lbKeywords.SelectedIndex == -1)
            {
                MessageBox.Show("No Selected Keyword to add; Sorry!");
                return;

            }
            else
            {
                String keyItem = lbKeywords.SelectedItem.ToString();
                //currently only one keyword is allowed for search
                lbSelectedKeywords.Items.Clear();
                if (!lbSelectedKeywords.Items.Contains(keyItem))
                {
                    lbSelectedKeywords.Items.Add(keyItem);
                }
                btnK.BorderBrush = new SolidColorBrush(Colors.Green);
            }
            // and the null,null saga continues, I should find a neater solution here!!!!
            fillSearchSummary(null, null);
        }

        private void btnRemoveKeyword_Click(object sender, RoutedEventArgs e)
        {
            while (lbSelectedKeywords.SelectedItem != null)
            {
                lbSelectedKeywords.Items.Remove(lbSelectedKeywords.SelectedItem);

            }
            fillSearchSummary(null, null);

            if (lbSelectedKeywords.Items.Count < 1)
            {
                btnK.BorderBrush = new SolidColorBrush(Colors.Cyan);
            }
        }

        private void webservices_update(object sender, RoutedEventArgs e)
        {
            lbSelectedWebservices.Items.Clear();
            foreach (ListItem item in lbWebServices.Items)
            {
                if (item.IsChecked)
                {
                    lbSelectedWebservices.Items.Add(item.Name);
                }
            }
            int no = lbWebServices.Items.Count();
            if (lbSelectedWebservices.Items.Count == no)
            {
                lbSelectedWebservices.Items.Clear();
                lbSelectedWebservices.Items.Add("All Webservices");
            }
            //trigger for search summary
            fillSearchSummary(null, null);
        }

        private void datepickStart_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            fillSearchSummary(null, null);
        }

        private void datepickEnd_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            fillSearchSummary(null, null);
        }

        private void btnDatesReset_Click(object sender, RoutedEventArgs e)
        {
            datepickEnd.SelectedDate = DateTime.Now;
            datepickStart.SelectedDate = DateTime.Now.AddYears(-1);
            fillSearchSummary(null, null);
        }
        private void btnColor()
        {
            btnA.BorderBrush = new SolidColorBrush(Colors.Green);
            btnB.BorderBrush = new SolidColorBrush(Colors.Green);
            btnW.BorderBrush = new SolidColorBrush(Colors.Green);
        }

        private void btnK_Click(object sender, RoutedEventArgs e)
        {
            if (lbl_Keywords_Value.Text == "")
            {
                tabSearch.SelectedIndex = 2;
            }
        }
        Popup popDG;
        //trial for carrying out the search
        //at trial stage only
        //settle the code once search starts working ok
        private void btnRunSearch_Click(object sender, RoutedEventArgs e)
        {
            //check for selected area
            if (txtboxALat.Text == "" || txtboxALong.Text == "" || txtboxBLat.Text == "" || txtboxBLong.Text == "")
            {
                MessageBox.Show("Hey, you forgot to select the area on Map, its easy, Press Control(Key) and drag a rectangle with left button mouse");
                return;
            }

            //check availability of keywords
            if (lbSelectedKeywords.Items.Count < 1)
            {
                tabSearch.SelectedIndex = 2;
                MessageBox.Show("Oops! I cant find the keyword, Please select a valid Keyword for search");
                return;
            }
            
            //initiate the popup form
            popDG = new Popup();
            waitForm form = new waitForm();
            form.BackgroundWorker = bw;
            popDG.Child = form;
            this.LayoutRoot.Children.Add(popDG);
            popDG.VerticalOffset = 200;
            popDG.HorizontalOffset = 200;
            popDG.IsOpen = true;

            this.IsEnabled = false;
            //popup trial ends
            SearchCriteria parameters = GetSearchParameters();

            //shift quickly to tab showing series data availability
            tabSearch.SelectedIndex = 3;
            //start the backgroundworker; first check if backgroundworker is already busy
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync(parameters);
            }
            //reset the datagrid
            dgSeriesList.ItemsSource = null;

            //reset the pins layer
            List<UIElement> elementsToRemove = new List<UIElement>();
            List<UIElement> pushpinToRemove = new List<UIElement>();
            foreach (UIElement element in mapDG.Children)
            {
                var mapLayer = element as MapLayer;
                if (mapLayer != null)
                //"pinsSeriesFound"
                {
                    if (mapLayer.Name == "pinsSeriesFound")
                    {
                        foreach (UIElement p in mapLayer.Children)
                        {
                            if (p is Pushpin)
                            {
                                pushpinToRemove.Add(p);
                            }
                        }
                        foreach (UIElement pin in pushpinToRemove) mapLayer.Children.Remove(pin);
                    }
                    elementsToRemove.Add(mapLayer);
                }
            }
            foreach (UIElement el in elementsToRemove)
            {
                mapDG.Children.Remove(el);
            }
        }

        //for controlling the border brush color
        
        //Run the Search///data adopted from HydroDesktop Desktop version
        private SearchCriteria GetSearchParameters()
        {
            var SearchCriterion = new SearchCriteria();
            //get the start date
            SearchCriterion.startDate = datepickStart.SelectedDate.Value;

            //get the end date
            SearchCriterion.endDate = datepickEnd.SelectedDate.Value;

            //get the keywords
            
            foreach (var item in lbSelectedKeywords.Items)
            {
                SearchCriterion.keywords.Add(item.ToString());
            }
            
            
            //get the webservices IDs
            if (IsAllWebservicesSelected() == true)
            {
                SearchCriterion.serviceIDs.Clear();
                //MessageBox.Show("all");
            }
            else
            {
                //MessageBox.Show("some");
                listBox1.Items.Clear();
                SearchCriterion.serviceIDs.Clear();
                foreach (ListItem it in lbWebServices.Items)
                {
                    if (it.IsChecked)
                    {
                        //MessageBox.Show(lbWebServices.Items.IndexOf(it).ToString());
                        listBox1.Items.Add(lbWebServicesSupport.Items[lbWebServices.Items.IndexOf(it)]);
                        SearchCriterion.serviceIDs.Add(Convert.ToInt32(lbWebServicesSupport.Items[lbWebServices.Items.IndexOf(it)]));
                        //SearchCriterion.serviceIDs.Add(lbWebServices.Items.IndexOf(it));
                    }
                }
            }
            //get the HIS Central URL
            SearchCriterion.hisCentralURL = "http://hiscentral.cuahsi.org/webservices/hiscentral.asmx";
            //get the area coordinates
            GetSearchArea(SearchCriterion);

            return SearchCriterion;
        }
        //Get search area by A & B Lat/Longs
        public void GetSearchArea(SearchCriteria SearchCriterion)
        {
            object areaParameter = SearchCriterion.areaParameter;


            //ArrayList rectangleCoordinates = new ArrayList();
            var bBox = new SearchCriteria.AreaRectangle
            {
                xMin = Convert.ToDouble(txtboxALong.Text),
                xMax = Convert.ToDouble(txtboxBLong.Text),
                yMin = Convert.ToDouble(txtboxBLat.Text),
                yMax = Convert.ToDouble(txtboxALat.Text),
            };
            areaParameter = bBox;

            //to assign the area parameter
            SearchCriterion.areaParameter = areaParameter;
            return;
        }


        //returns true, if the search option is 'All WebServices Selected'
        bool IsAllWebservicesSelected()
        {
            if (lbSelectedWebservices.Items[0].ToString() == "All Webservices")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //MapLayer usaStates = new MapLayer();
            //Shape 
        }

        private void cbSelectArea_Checked(object sender, RoutedEventArgs e)
        {
            if (cbSelectArea.IsChecked == true)
            {
                gridAreaSelection.Visibility = Visibility.Visible;
                rectSelectMapArea.Visibility = Visibility.Visible;
                rectSelectPushpins.Visibility = Visibility.Collapsed;
            }
            else
            {
                gridAreaSelection.Visibility = Visibility.Collapsed;
                rectSelectMapArea.Visibility = Visibility.Collapsed;
                rectSelectPushpins.Visibility = Visibility.Visible;
            }
        }

        private void cbEnableSelection_Click(object sender, RoutedEventArgs e)
        {

            if (cbEnableSelection.IsChecked == true)
            {
                if (cbSelectArea.IsChecked == true)
                {
                    cbSelectArea.IsChecked = false;
                    gridAreaSelection.Visibility = Visibility.Collapsed;
                    rectSelectMapArea.Visibility = Visibility.Collapsed;
                    rectSelectPushpins.Visibility = Visibility.Visible;
                }
            }
            else
            {
                if (cbSelectArea.IsChecked == false)
                {
                    cbSelectArea.IsChecked = true;
                    gridAreaSelection.Visibility = Visibility.Visible;
                    rectSelectMapArea.Visibility = Visibility.Visible;
                    rectSelectPushpins.Visibility = Visibility.Collapsed;
                }
            }
        }
        #region export data-series data to CSV
        private void btnExportCSV_Click(object sender, RoutedEventArgs e)
        {
            if (dgSeriesList.ItemsSource != null)
            {
                //string data = ExportDataGrid(true, historyDataGrid);
                string data = ExportDataGrid(true, dgSeriesList);
                SaveFileDialog sfd = new SaveFileDialog()
                {
                    DefaultExt = "csv",
                    Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
                    FilterIndex = 1
                };
                if (sfd.ShowDialog() == true)
                {
                    using (Stream stream = sfd.OpenFile())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(data); writer.Close();
                        }
                        stream.Close();
                    }
                }
            }
        }

        private string FormatCSVField(string data)
        {
            return String.Format("\"{0}\"",
              data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
        }

        public string ExportDataGrid(bool withHeaders, DataGrid grid)
        {
            string colPath;
            System.Reflection.PropertyInfo propInfo;
            System.Windows.Data.Binding binding;
            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            System.Collections.IList source = (grid.ItemsSource as System.Collections.IList);
            if (source == null) return "";
            List<string> headers = new List<string>();
            grid.Columns.ToList().ForEach(col =>
            {
                if (col is DataGridBoundColumn)
                {
                    headers.Add(FormatCSVField(col.Header.ToString()));
                }
            });
            strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
            foreach (Object data in source)
            {
                List<string> csvRow = new List<string>();
                foreach (DataGridColumn col in grid.Columns)
                {
                    if (col is DataGridBoundColumn)
                    {
                        binding = (col as DataGridBoundColumn).Binding;
                        colPath = binding.Path.Path; propInfo = data.GetType().GetProperty(colPath);
                        if (propInfo != null)
                        {
                            csvRow.Add(FormatCSVField(propInfo.GetValue(data, null).ToString()));
                        }
                    }
                }
                strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
            }
            return strBuilder.ToString();
        }
        #endregion

        #region download data series
        childwindowTrial cwT;
        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            //first check for data-availability
            if (dgSeriesList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please Select at least single data-series row to download.");
                return;
            }
            //set main datagrid source to null
            datagridMainTable.ItemsSource = null;
            readresultDG.Clear();
            //shift the download function to background worker
            bwdownload.RunWorkerAsync();

            //this is trial code for handling child windows
            cwT = new childwindowTrial();

            //reset the datagrids and graph
            cwT.dgProgressReport.ItemsSource = null;
            datagridIndexTable.ItemsSource = null;
            datagridGraphIndex.ItemsSource = null;
            ((LineSeries)timeseriesGraph.Series[0]).ItemsSource = null;
            readresultDGIndex.Clear();

            //cwT.dgProgressReport.ItemsSource = dgSeriesList.ItemsSource;
            cwT.DataContext = dgSeriesList.ItemsSource;
            cwT.dgProgressReport.ItemsSource = getTargetSeriesDG;
            cwT.Show();
            /////
            ////////add to datagrid index table
            //////datagridIndexTable.ItemsSource = getTargetSeriesDG;
            ////////add to datagrid Graph Index
            //////datagridGraphIndex.ItemsSource = getTargetSeriesDG;
            
        }
        void bwdownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // throw new NotImplementedException();
        }

        void bwdownload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // throw new NotImplementedException();
            
        }
        
        private ObservableCollection<readResult> readresultDG = new ObservableCollection<readResult>();
        private ObservableCollection<readresultIndex> readresultDGIndex = new ObservableCollection<readresultIndex>();
        private ObservableCollection<getTargetSeries> getTargetSeriesDG = new ObservableCollection<getTargetSeries>();

        //public List<getTargetSeries> _gettargerSeries = new List<getTargetSeries>();
        void bwdownload_DoWork(object sender, DoWorkEventArgs e)
        {
            //combination of site-code and variable-code is the unique set criterion for download
            ObservableCollection<readResult> readresultDG = new ObservableCollection<readResult>();
            ObservableCollection<readresultIndex> readresultDGIndex = new ObservableCollection<readresultIndex>();

            List<DownloadInfo> downloadList = new List<DownloadInfo>();
            List<string> fileNameList = new List<string>();
            
            if (dgSeriesList.SelectedItems.Count > 0)
            {
                //clear the observable collection on each download request
                Dispatcher.BeginInvoke(new Action(delegate()
                {
                    getTargetSeriesDG.Clear();
                }));
                //trigger for all selected items a download string
                foreach (var ritem in dgSeriesList.SelectedItems)
                {
                    var cartdownload = ritem as SeriesDataCart;
                    if (cartdownload != null)
                    {
                        //if (cart.Latitude == x && cart.Longitude == y)
                        //    dgSeriesList.SelectedItems.Add(cart);
                        DownloadInfo dinfo = new DownloadInfo();
                        dinfo.SiteName = cartdownload.SiteName.ToString();
                        dinfo.FullSiteCode = cartdownload.SiteCode.ToString();
                        dinfo.FullVariableCode = cartdownload.VariableCode.ToString();
                        dinfo.Wsdl = cartdownload.ServURL.ToString();
                        dinfo.StartDate = cartdownload.BeginDate;
                        dinfo.EndDate = cartdownload.EndDate;
                        dinfo.VariableName = cartdownload.VariableName.ToString();
                        dinfo.Latitude = Convert.ToDouble(cartdownload.Latitude);
                        dinfo.Longitude = Convert.ToDouble(cartdownload.Longitude);
                        
                        //add it to the list for datagrid in child window
                        var _getTargetSeries = new getTargetSeries();
                        _getTargetSeries.Val = true;
                        _getTargetSeries.Server = cartdownload.ServCode.ToString();
                        _getTargetSeries.Site_Code = cartdownload.SiteCode.ToString();
                        _getTargetSeries.Var_Code = cartdownload.VariableCode.ToString();
                        _getTargetSeries.Value_Count = cartdownload.ValueCount.ToString();
                        _getTargetSeries.Site_Name = cartdownload.SiteName.ToString();

                        Dispatcher.BeginInvoke(new Action(delegate()
                        {
                            getTargetSeriesDG.Add(_getTargetSeries);
                        }));

                        StringBuilder url = new StringBuilder();
                        url.Append("http://www.hydroweb.info/getservice.php");
                        //url.Append("http://http://www.westernconsortium.org/his/getservice.php");
                        url.Append("?url=" + HttpUtility.UrlEncode(dinfo.Wsdl));
                        url.Append("&site=" + HttpUtility.UrlEncode(dinfo.FullSiteCode));
                        url.Append("&variable=" + HttpUtility.UrlEncode(dinfo.FullVariableCode));
                        url.Append("&startdate=" + HttpUtility.UrlEncode(dinfo.StartDate.ToString("yyyy-MM-dd")));
                        url.Append("&enddate=" + HttpUtility.UrlEncode(dinfo.EndDate.ToString("yyyy-MM-dd")));

                        //fire the HTTP Soap Request
                        HttpSOAPRequest(url.ToString());
                    }
                }
            }
        }

        void HttpSOAPRequest(string turl)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(turl);
            req.BeginGetResponse(new AsyncCallback(ReadCback), req);
        }

        private static Stream CopyStream(Stream inputStream)
        {
            const int readSize = 256; 
            byte[] buffer = new byte[readSize]; 
            MemoryStream ms = new MemoryStream(); 
            int count = inputStream.Read(buffer, 0, readSize); 
            while (count > 0) 
            { 
                ms.Write(buffer, 0, count); 
                count = inputStream.Read(buffer, 0, readSize); 
            } 
            ms.Seek(0, SeekOrigin.Begin); 
            return ms; 
        }

        private void ReadCback(IAsyncResult asynchronousResult)
        {
            try
            {
                List<readResult> readResultSeries = new List<readResult>();
                List<readresultIndex> readResultSeriesIndex = new List<readresultIndex>();

                HttpWebRequest requestData =
                  (HttpWebRequest)asynchronousResult.AsyncState;

                HttpWebResponse resp =
                  (HttpWebResponse)requestData.EndGetResponse(asynchronousResult);
                
                Stream responseStream = CopyStream(resp.GetResponseStream());
                //use first copy
                StreamReader sR = new StreamReader(responseStream);
                long startPosition = sR.BaseStream.Position;//del
                XmlReader dgR = XmlReader.Create(sR);
                    
                while (dgR.Read())
                {
                    if (dgR.NodeType == XmlNodeType.Element)
                    {
                        if (dgR.Name == "timeSeriesResponse")
                        {
                            readResultSeries = readFinalResult(dgR);
                            //readResultSeriesIndex = readFinalResultIndex(dgR);
                            Dispatcher.BeginInvoke(new Action(delegate()
                            {
                                foreach (var rowitem in readResultSeries)
                                {
                                    readresultDG.Add(rowitem);
                                }
                                //foreach (var rowitemindex in readResultSeriesIndex)
                                //{
                                //    readresultDGIndex.Add(rowitemindex);
                                //}
                            }));
                        }
                    }//if statement ends
                }
                //use second copy
                responseStream.Seek(0, SeekOrigin.Begin);

                StreamReader sRR = new StreamReader(responseStream);
                XmlReader dgRR = XmlReader.Create(sRR);
                    
                while (dgRR.Read())
                {
                    if (dgRR.NodeType == XmlNodeType.Element)
                    {
                        if (dgRR.Name == "timeSeriesResponse")
                        {
                            //readResultSeries = readFinalResult(dgRR);
                            readResultSeriesIndex = readFinalResultIndex(dgRR);
                            Dispatcher.BeginInvoke(new Action(delegate()
                            {
                                
                                foreach (var rowitemindex in readResultSeriesIndex)
                                {
                                    readresultDGIndex.Add(rowitemindex);
                                }
                            }));
                        }
                    }//if statement ends
                }
               
                datagridMainTable.Dispatcher.BeginInvoke(new Action(delegate()
                {
                    //add to datagrid main table
                    datagridMainTable.ItemsSource = readresultDG;
                    //cwT.Close();
                    tabMain.SelectedIndex = 1;
                }));
                datagridMainTable.Dispatcher.BeginInvoke(new Action(delegate()
               {
                   //add to datagrid index table
                   datagridIndexTable.ItemsSource = readresultDGIndex;
                   //add to datagrid Graph Index
                   datagridGraphIndex.ItemsSource = readresultDGIndex;
                   //add to child window thus mapping the progress
                   
                   cwT.Close();
                   //cwT.dgProgressReport.ItemsSource = readresultDGIndex;
               }));
            }
            catch (Exception e)
            {
                Dispatcher.BeginInvoke(new Action(delegate()
                {
                    //MessageBox.Show(e.Message);
                    //MessageBox.Show("I am skipping this download as Server seems to be down. Error Message: " + e.Message);
                }));
            }
        }

        private List<readResult> readFinalResult(XmlReader rr)
        {
            List<readResult> readResultSeries = new List<readResult>();
            String sName = "";
            String net = "";
            String scode = "";
            String vname = "";
            String vType = "";
            String dType = "";
            String uni = "";
            //String unA = "";
            //String unT = "";
            String ndv = "";

            while (rr.Read())
            {
                string nodename = rr.Name.ToLower();
                //get the siteName
                if (rr.Name == "siteName")
                {
                    sName = rr.ReadInnerXml();
                }
                //get the siteCode
                if (rr.Name == "siteCode")
                {
                    net = rr.GetAttribute("network");
                    scode = rr.ReadInnerXml();
                }
                //get the Variable Name
                if (rr.Name == "variableName")
                {
                    vname = rr.ReadInnerXml();
                }
                //get the ValueType
                if (rr.Name == "valueType")
                {
                    vType = rr.ReadInnerXml();
                }
                //get the DataType
                if (rr.Name == "dataType")
                {
                    dType = rr.ReadInnerXml();
                }
                //get the Units
                if (rr.Name == "units")
                {
                    uni = rr.ReadInnerXml();
                }
                //get the NoDataValues
                if (rr.Name == "NoDataValue")
                {
                    ndv = rr.ReadInnerXml();
                }

                if (rr.Name == "value")
                {
                    while (rr.Name == "value")
                    {
                        readResult rSeries = new readResult();
                        rSeries.siteName = sName;
                        rSeries.siteCode = scode;
                        rSeries.networkCode = net;
                        rSeries.varName = vname;
                        rSeries.valType = vType;
                        rSeries.dataType = dType;
                        rSeries.un = uni;
                        rSeries.nDatavalue = ndv;
                        rSeries.valuedateTime = Convert.ToDateTime(rr.GetAttribute("dateTime"));
                        rSeries.mainValue = rr.ReadInnerXml();
                        readResultSeries.Add(rSeries);
                    }
                }
            }//while (rr.Read() ends....
            
            return readResultSeries;
            //return null;
        }
       

        //for index
        private List<readresultIndex> readFinalResultIndex(XmlReader rr)
        {
            readresultIndex rseriesIndex = new readresultIndex();
            List<readresultIndex> rseriesIndexSeries = new List<readresultIndex>();
            while (rr.Read())
            {
                string nodename = rr.Name.ToLower();

                if (rr.Name == "siteName")
                {
                    rseriesIndex.Site_Name = rr.ReadInnerXml();
                }
                if (rr.Name == "siteCode")
                {
                    rseriesIndex.Network_Code = rr.GetAttribute("network");
                    rseriesIndex.Site_Code = rr.ReadInnerXml();
                }
                if (rr.Name == "variableName")
                {
                    rseriesIndex.Var_Name = rr.ReadInnerXml();
                    //rseriesIndex.Value = false;
                }
            }
            rseriesIndexSeries.Add(rseriesIndex);
            return rseriesIndexSeries;
        }

        #endregion download data series

        private void colorpushpinsblue()
        {
            foreach (UIElement element in mapDG.Children)
            {
                var mapLayer = element as MapLayer;
                if (mapLayer != null)
                //"pinsSeriesFound"
                {
                    if (mapLayer.Name == "pinsSeriesFound")
                    {
                        foreach (var p in mapLayer.Children)
                        {
                            var pin = p as Pushpin;
                            pin.Background = new SolidColorBrush(Colors.Blue);
                        }
                    }
                }
            }
        }

        private void dgSeriesList_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //check for pushpin selection mode
            if (cbEnableSelection.IsChecked == true)
            {
                colorpushpinsblue();
                if (dgSeriesList.ItemsSource != null)
                {
                    foreach (var rowitem in dgSeriesList.SelectedItems)
                    {
                        var cart = rowitem as SeriesDataCart;
                        if (cart != null)
                        {  
                            foreach (UIElement element in mapDG.Children)
                            {
                                var mapLayer = element as MapLayer;
                                if (mapLayer != null)
                                //"pinsSeriesFound"
                                {
                                    if (mapLayer.Name == "pinsSeriesFound")
                                    {
                                        //next segregate the ones that are selected and color them orange
                                        foreach (var p in mapLayer.Children)
                                        {
                                            var pin = p as Pushpin;

                                            if (p != null)
                                            {
                                                var z = pin.Location;
                                                double x = z.Latitude;
                                                double y = z.Longitude;
                                                if (cart.Latitude == x && cart.Longitude == y)
                                                {
                                                    pin.Background = new SolidColorBrush(Colors.Orange);
                                                }
                                            }
                                        }

                                    }
                                }
                                int count = 0;
                                count = dgSeriesList.SelectedItems.Count;
                                if (count > 0) lblSelectedPins.Content = "Data Series Selected:" + count;
                                else lblSelectedPins.Content = "No Data Series Selected";
                            }

                        }//ends
                    }

                }
            }
            
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            int count = 0;
            count = datagridMainTable.ItemsSource.OfType<object>().Count();
            if (count > 0) lblTotalTableRows.Content = "Total rows:" + count;
            else lblTotalTableRows.Content = "No Data available";
        }

        private void datagridGraphIndex_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //first clear the graph
            ((LineSeries)timeseriesGraph.Series[0]).ItemsSource = null;

            DataGrid graphGrid = sender as DataGrid;
            //create the new list of KeyVALUEPair
            List<KeyValuePair<DateTime, Double>> dataGraph = new List<KeyValuePair<DateTime, Double>>();
            //List<readResult> dataGraph = new List<readResult>();
            var ritems = graphGrid.SelectedItem as readresultIndex;
            if (datagridGraphIndex.SelectedItems.Count == 1)
            {
                foreach (var ritem in datagridMainTable.ItemsSource)
                {
                    var cItems = ritem as readResult;
                    if (cItems.siteCode == ritems.Site_Code && cItems.varName == ritems.Var_Name)
                    {
                        if (cItems.mainValue == cItems.nDatavalue || cItems.mainValue == "-999999") // this will filter the no data values
                        {}
                        else dataGraph.Add(new KeyValuePair<DateTime, Double>(cItems.valuedateTime, Convert.ToDouble(cItems.mainValue)));
                    }
                    
                }
                //Create the graph here
                //((LineSeries)timeseriesGraph.Series[0]).ItemsSource = dataGraph;
                Random rnd = new Random();
                if (dataGraph.Count > 500)
                {
                    ((LineSeries)timeseriesGraph.Series[0]).ItemsSource = dataGraph.OrderBy(x => rnd.Next()).Take(500);
                }
                else
                {
                    ((LineSeries)timeseriesGraph.Series[0]).ItemsSource = dataGraph;
                }

            }
        }

        private void btnExportdatatoCSV_Click(object sender, RoutedEventArgs e)
        {
            if (datagridMainTable.ItemsSource != null)
            {
                //string data = ExportDataGrid(true, historyDataGrid);
                string data = ExportDataGrid(true, datagridMainTable);
                SaveFileDialog sfd = new SaveFileDialog()
                {
                    DefaultExt = "csv",
                    Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
                    FilterIndex = 1
                };
                if (sfd.ShowDialog() == true)
                {
                    using (Stream stream = sfd.OpenFile())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(data); writer.Close();
                        }
                        stream.Close();
                    }
                }
            }
        }

        private void btnsurveySubmit_Click(object sender, RoutedEventArgs e)
        {
           
            //first capture the input parameters
            surveyinput sin = new surveyinput();
            
            foreach (RadioButton rb in sprb1.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb1 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb2.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb2 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb3.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb3 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb4.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb4 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb5.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb5 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb6.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb6 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb7.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb7 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb8.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb8 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb9.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb9 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb10.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb10 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb11.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb11 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb12.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb12 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb13.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb13 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb14.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb14 = rb.Name.ToString();
                }
            }
            foreach (RadioButton rb in sprb15.Children)
            {
                if (rb.IsChecked == true)
                {
                    sin.rb15 = rb.Name.ToString();
                }
            }
            if (textGivenname.Text != "")
            {
                sin.givenname = textGivenname.Text;
            }
            else
            {
                MessageBox.Show("Name can not be blank!");
                textGivenname.Focus();
                return;
            }
            if (textEmailid.Text.Length == 0)
            {
                MessageBox.Show("Email can not be blank!");
                textEmailid.Focus();
                return;
            }
            else if (!Regex.IsMatch(textEmailid.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
            {
                // An invalid email format was entered
                MessageBox.Show("Enter a valid email.");
                textEmailid.Select(0, textEmailid.Text.Length);
                textEmailid.Focus();
                return;
            }
            else
            {
                sin.emailid = textEmailid.Text;
            }


            StringBuilder surl = new StringBuilder();
            surl.Append("http://www.hydroweb.info/survey_vars.php");
            surl.Append("?givenname=" + HttpUtility.UrlEncode(sin.givenname));
            surl.Append("&emailid=" + HttpUtility.UrlEncode(sin.emailid));
            surl.Append("&rb1=" + HttpUtility.UrlEncode(sin.rb1));
            surl.Append("&rb2=" + HttpUtility.UrlEncode(sin.rb2));
            surl.Append("&rb3=" + HttpUtility.UrlEncode(sin.rb3));
            surl.Append("&rb4=" + HttpUtility.UrlEncode(sin.rb4));
            surl.Append("&rb5=" + HttpUtility.UrlEncode(sin.rb5));
            surl.Append("&rb6=" + HttpUtility.UrlEncode(sin.rb6));
            surl.Append("&rb7=" + HttpUtility.UrlEncode(sin.rb7));
            surl.Append("&rb8=" + HttpUtility.UrlEncode(sin.rb8));
            surl.Append("&rb9=" + HttpUtility.UrlEncode(sin.rb9));
            surl.Append("&rb10=" + HttpUtility.UrlEncode(sin.rb10));
            surl.Append("&rb11=" + HttpUtility.UrlEncode(sin.rb11));
            surl.Append("&rb12=" + HttpUtility.UrlEncode(sin.rb12));
            surl.Append("&rb13=" + HttpUtility.UrlEncode(sin.rb13));
            surl.Append("&rb14=" + HttpUtility.UrlEncode(sin.rb14));
            surl.Append("&rb15=" + HttpUtility.UrlEncode(sin.rb15));
            
            //Prepare web request
            HttpWebRequest saveSurveydata = (HttpWebRequest)WebRequest.Create(surl.ToString());
            //saveSurveydata.Method = "POST";

            saveSurveydata.BeginGetResponse(new AsyncCallback(GetResult), saveSurveydata);
            
            //invoke the child window
            ChildWindow cwthank = new inputSurvey();
            cwthank.Show();

        }
        private void GetResult(IAsyncResult asynchronousResult)
        {
            HttpWebRequest requestDatas =
                  (HttpWebRequest)asynchronousResult.AsyncState;

            //HttpWebResponse respe =
            //  (HttpWebResponse)requestDatas.EndGetResponse(asynchronousResult);

            //MessageBox.Show(respe.ToString());
        }


        private void btnHelparea_Click(object sender, RoutedEventArgs e)
        {
            ChildWindow helpselectarea = new help_selectarea();
            helpselectarea.Show();
        }

        private void btnDatewebservices_Click(object sender, RoutedEventArgs e)
        {

            ChildWindow helpselectweb = new help_selectweb();
            helpselectweb.Show();
        }

        private void btnHelpkeyword_Click(object sender, RoutedEventArgs e)
        {
            ChildWindow helpkey = new help_selectkeywords();
            helpkey.Show();
        }

        private void btnLoadshape_Click(object sender, RoutedEventArgs e)
        {
            if (cbWatershedvalue.SelectedIndex >= 0 && rbWater.IsChecked == true)
            {
                String qFeature = cbWatershedvalue.SelectedItem.ToString();
                //MessageBox.Show(qFeature);
                String sqlQuery = "Select * from us_huc8b where reg_name = " + "'" + qFeature + "'";
                //MessageBox.Show(sqlQuery);
                textString.Text = sqlQuery;
            }
        }
    }
}
